<template>
  <view>
    <view class="chat-main">
      <scroll-view class="chat-message" :scroll-y="true" :scroll-into-view="childrenId">
        <view v-for="(message, index) in messages" :key="message.id" :id="`chat-message-item-${index}`">
          <view class="chat-message-item">
            <image
              :class="['chat-avatar', `chat-avatar-${message.from == userInfo.id ? 'me' : 'to'}`]"
              :src="getImage(message.from == userInfo.id ? userInfo.avatar : currentToUser.avatarId)"></image>
            <view :class="['chat-message-content', `chat-message-content-${message.from == userInfo.id ? 'me' : 'to'}`]">
              <view class="chat-message-content-text">{{ message.content }}</view></view
            >
          </view>
        </view>
      </scroll-view>
      <view class="chat-footer">
        <uni-icons type="videocam-filled" size="30" @click="call"></uni-icons>
        <uni-icons type="image-filled" size="30" @click="chooseImage"></uni-icons>
        <uni-easyinput autoHeight type="textarea" placeholder="请输入消息" v-model="message"> </uni-easyinput>
        <button class="chat-send-btn" @click="sendMessage(message, 2)">发送</button>
      </view>
    </view>
    <uni-popup ref="videoCall" type="center" class="video-call">
      <text class="title">通话时间：{{ time }}</text>
      <video
        ref="localVideo"
        :show-center-play-btn="false"
        :show-play-btn="false"
        is-live
        :controls="false"
        :http-cache="false"
        class="local-video"
        autoplay></video>
      <video
        ref="remoteVideo"
        :http-cache="false"
        :show-center-play-btn="false"
        :show-play-btn="false"
        :controls="false"
        is-live
        class="remote-video"
        autoplay></video>
      <button @click="acceptVideo" type="primary">接听</button>
      <button @click="close" type="warn">挂断</button>
    </uni-popup>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters(['userInfo']),
  },
  data() {
    return {
      // 当前聊天对象
      currentToUser: {},
      // 消息列表
      messages: [],
      // 分页
      current: 1,
      // 页长
      size: 20,
      // 总数
      total: 0,
      // 滚动条子组件id
      childrenId: '',
      //待发送的消息
      message: '',
      // 计时器
      flag: null,
      // 通话时间
      time: '00:00:00',
      // 当前时间
      currentTime: '',
      // 通话中
      calling: false,
      //文件列表
      fileList: [],
    }
  },
  onLoad(option) {
    this.currentToUser = { id: option.id, userName: option.name, avatarId: option.avatarId }
    uni.setNavigationBarTitle({
      title: option.name,
    })
  },
  onShow() {
    this.$store.dispatch('message/initSocket', this.onMessage, this.onError)
    this.moreMessage(false)
    this.scrollToBottom()
  },
  methods: {
    // 接收消息
    onMessage(e) {
      var data = JSON.parse(e.data)
      switch (data.type) {
        //对话消息
        case 2:
          console.log(data)
          this.messages.push(data)
          this.scrollToBottom()
          break
        //收到邀请
        case 3:
          this.$refs.videoCall.open()
          this.calling = false
          break
        //接收邀请
        case 4:
          this.$store.dispatch('message/requestVideo', this.currentToUser.userId)
          break
        //offer阶段
        case 5:
          this.$store
            .dispatch('message/offer', {
              localVideo: this.$refs.localVideo,
              remoteVideo: this.$refs.remoteVideo,
              to: this.currentToUser.userId,
            })
            .then((response) => {
              console.log(`offer`, response)
            })
          break
        //answer阶段
        case 6:
          this.$store
            .dispatch('message/answer', {
              localVideo: this.$refs.localVideo,
              remoteVideo: this.$refs.remoteVideo,
              offer: data.content,
              to: this.currentToUser.userId,
            })
            .then((response) => {
              console.log(`answer`, response)
            })
          break
        //设置answer
        case 7:
          this.$store.dispatch('message/localSetAnswer', data.content)
          break
        //设置candidate
        case 8:
          this.$store.dispatch('message/candidate', { candidate: data.content.candidate })
          this.start()
          this.calling = true
          break
        //拒绝&结束通话
        case 9:
          this.close(false)
          break
        //文件消息
        case 10:
          this.messages.push(data)
          this.scrollToBottom()
          break
      }
    },
    //滚动到底部
    scrollToBottom() {
      let len = this.messages.length
      this.childrenId = `chat-message-item-${len - 1}`
    },
    // 错误
    onError(e) {
      console.log(e)
    },

    //点击显示更多消息
    moreMessage(more) {
      this.current = more ? this.current + 1 : 1
      this.$store
        .dispatch('message/getMessageList', {
          to: this.currentToUser.id,
          me: this.userInfo.id,
          page: this.current,
          size: this.size,
        })
        .then((response) => {
          this.messages = more ? [...response.data, ...this.messages] : response.data
          this.total = response.other.pageSize
          if (!more) {
            this.scrollToBottom()
          }
        })
    },
    //发送消息
    sendMessage(message, type) {
      var newMsg = {
        to: this.currentToUser.id,
        type: type,
        from: this.userInfo.id,
        content: message,
      }
      console.log(newMsg)
      this.$store.dispatch('message/sendMessage', newMsg).then((response) => {
        if (response.success) {
          this.messages.push(newMsg)
        }
      })
      this.message = ''
      this.scrollToBottom()
    },
    // 获取头像
    getImage(id) {
      return `${process.env.VUE_APP_ORIGIN_API}fileService/file/download?id=${id}`
    },
    // 视频通话
    call() {
      this.calling = false
      this.$refs.videoCall.open()
      this.sendMessage('', 3)
    },
    // 结束通话
    close(send) {
      this.$store.dispatch('message/close', this.$refs.localVideo).then(() => {
        this.$refs.videoCall.close()
        if (send) {
          this.sendMessage(this.time, 9)
        }
      })
      this.time = this.currentTime
      this.reset()
    },
    //接受呼叫
    acceptVideo() {
      // console.log(1)
      this.sendMessage('', 4)
    },
    //开始计时
    start() {
      var second = 0
      var minute = 0
      var hour = 0
      this.flag = setInterval(() => {
        second++
        if (second >= 60) {
          second = 0
          minute++
        }

        if (minute >= 60) {
          minute = 0
          hour++
        }
        this.currentTime = this.fillZero(hour) + ':' + this.fillZero(minute) + ':' + this.fillZero(second)
      }, 1000)
    },
    //重新计时
    reset() {
      window.clearInterval(this.flag)
      this.hour = 0
      this.minute = 0
      this.second = 0
      this.currentTime = '00:00:00'
    },
    //暂停计时
    end() {
      this.flag = clearInterval(this.flag)
    },
    //补零
    fillZero(n) {
      return n < 10 ? '0' + n : n
    },
    // 上传文件
    uploadFile(event, file, fileList) {
      if (file == null) {
        return
      }
      this.$store.dispatch('file/uploadFile', file).then((response) => {
        if (response.success) {
          this.sendMessage(response.data, 10)
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.chat-main {
  .chat-message {
    // height: 1000rpx;
    height: calc(100vh - 400rpx);
    width: 100%;

    .chat-message-item {
      width: 100%;
      overflow: auto;
      height: fit-content;
      margin: 25rpx 0;
      .chat-message-content {
        height: fit-content;
        max-width: 60%;
        border: 1rpx solid #ccc;
        font-size: 40rpx;
        padding: 10rpx 20rpx;
        word-break: break-all;
        line-height: 2;
        border-radius: 10rpx;
        margin: 0 25rpx;
        &-text {
          max-width: 100%;
          height: fit-content;
          white-space: normal;
        }
        &-me {
          float: right;
          background-color: #67c23a;
          color: white;
        }
        &-to {
          float: left;
          background-color: white;
        }
      }
      .chat-avatar {
        width: 100rpx;
        height: 100rpx;
        border-radius: 10rpx;
        &-me {
          float: right;
        }
        &-to {
          float: left;
        }
      }
    }
  }
  .chat-footer {
    width: 100%;
    height: 300rpx;
    bottom: 0;
    position: fixed;
    background-color: #fff;
    .chat-send-btn {
      width: 20%;
      margin-top: -100rpx;
      margin-right: 10rpx;
    }
  }
}
.video-call {
  // border: 1px red solid;
  width: 100%;
  height: 300rpx;
  .title {
    width: 100%;
    display: block;
    color: #fff;
    text-align: center;
  }
  .remote-video {
    width: 450rpx;
    margin-left: 100rpx;
    height: 800rpx;
    border: 1px red solid;
    // float: left;
  }
  .local-video {
    width: 150rpx;
    height: 150rpx;
    margin-left: 100rpx;
    border: 1px red solid;
    // float: left;
  }
}
</style>
